﻿namespace LS.Nc6.Core
{
    /// <summary>
    /// 数据库上下文对象
    /// </summary>
    public static class DbContext
    {
        /// <summary>
        /// SqlSugar 数据库实例
        /// </summary>
        public static readonly SqlSugarScope Instance = new(
            // 读取 appsettings.json 中的 ConnectionConfigs 配置节点
            App.GetConfig<List<ConnectionConfig>>("ConnectionConfigs")
            , db =>
            {
                // 这里配置全局事件，比如拦截执行 SQL
                db.Aop.OnLogExecuting = (sql, pars) =>
                {
                    Console.WriteLine("Sql:" + "\r\n\r\n" + UtilMethods.GetSqlString(db.CurrentConnectionConfig.DbType, sql, pars));
                };

                db.Aop.DataExecuting = (oldValue, entityInfo) =>
                {
                    // 新增操作
                    if (entityInfo.OperationType == DataFilterType.InsertByObject)
                    {
                        // 主键(long)-赋值雪花Id
                        //if (entityInfo.EntityColumnInfo.IsPrimarykey && entityInfo.EntityColumnInfo.PropertyInfo.PropertyType == typeof(long))
                        //{
                        //    var id = ((dynamic)entityInfo.EntityValue).Id;
                        //    if (id == null || id == 0)
                        //        entityInfo.SetValue(Yitter.IdGenerator.YitIdHelper.NextId());
                        //}
                        if (entityInfo.PropertyName == "CreateDate")
                            entityInfo.SetValue(DateTime.Now);
                        if (App.User != null)
                        {
                            if (entityInfo.PropertyName == "CreateBy")
                            {
                                var createUserId = ((dynamic)entityInfo.EntityValue).CreateBy;
                                if (createUserId == null || createUserId == 0)
                                    entityInfo.SetValue(App.User.FindFirst(ClaimConst.CLAINM_USERID)?.Value);
                            }
                            //if (entityInfo.PropertyName == "CreatedUserName")
                            //    entityInfo.SetValue(App.User.FindFirst(ClaimConst.CLAINM_NAME)?.Value);
                        }
                    }
                    // 更新操作
                    if (entityInfo.OperationType == DataFilterType.UpdateByObject)
                    {
                        if (entityInfo.PropertyName == "UpdateDate")
                            entityInfo.SetValue(DateTime.Now);
                        if (entityInfo.PropertyName == "UpdateBy")
                            entityInfo.SetValue(App.User?.FindFirst(ClaimConst.CLAINM_USERID)?.Value);
                      
                    }
                };
                List<Type> types = App.EffectiveTypes.Where(a => !a.IsAbstract && a.IsClass && a.GetCustomAttributes(typeof(SugarTable), true)?.FirstOrDefault() != null).ToList();

                // 配置加删除全局过滤器
                foreach (var entityType in types)
                {
                    if (entityType.GetProperty(CommonConst.DELETE_FIELD)!=null )
                    { //判断实体类中包含IsDeleted属性
                      //构建动态Lambda
                        var lambda = DynamicExpressionParser.ParseLambda
                        (new[] { Expression.Parameter(entityType, "it") },
                         typeof(bool), $" IsDeleted ==  @0",
                          0);
                        db.QueryFilter.Add(new TableFilterItem<object>(entityType, lambda)
                        {
                            IsJoinQuery = true
                        }); //将Lambda传入过滤器
                    }
                }
                

            });
    }
}